import React, {useState, useRef, useMemo} from 'react'
import {Empty} from 'antd'
import PicNameQuestion from './components/PicNameQuestion'
import shuffle from './lib/shuffle.js'
import useStudents from './hooks/useStudents.js'

export default ({history, location: {state: {classname}}}) => {
  const {students} = useStudents(classname)
  const [current, setCurrent] = useState(0)
  const wrongRef = useRef(0)
  const questions = useMemo(() => shuffle(students), [students])
  if(questions.length === 0) {
    return <Empty/>
  }
  const question = questions[current]
  const onNext = ({wrongCount}) => {
    wrongRef.current = wrongRef.current + wrongCount
    if(current === questions.length - 1) {
      history.push(`/result/${wrongRef.current}/${questions.length}`)
    } else {
      setCurrent(prev => prev + 1)
    }
  }
  return (
    <div style={{
      potition: 'relative'
    }}>
      <PicNameQuestion {...question} key={question.id}
                       classname={classname}
                       onNext={onNext}/>
    </div>
  )
}
